package com.zrrd.mybatis_02.common.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author WanJl
 * @version 1.0
 * @title SqlSessionFactoryUtil
 * @description
 * @create 2024/10/11
 */
public class SqlSessionFactoryUtil {
    /*
        私有的SQLSession工厂
    */
    private static SqlSessionFactory sqlSessionFactory;

    //因为static代码块里面的代码会在类加载的时候就进行加载。
    static {
        try {
            /*
                加载数据源，获取一个打开数据源文件的流
             */
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //根据SqlSessionFactoryBuilder创建sqlSessionFactory对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取SqlSession工厂对象的方法
     * @return
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    /**
     * 获取SqlSession
     * @return
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }

    /**
     * 获取SqlSession
     * @param autoCommit 自动提交事务
     * @return
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return getSqlSessionFactory().openSession(autoCommit);
    }
}
